package umputun.jutw;

import evgeniuz.VKActivity;
import gen1us.jutw.utils.CheckConfig;
import umputun.jutw.Process.from_twi.Processor;
import umputun.jutw.jabber.JabberClient;
import umputun.jutw.storage.FileStorage;
import umputun.jutw.storage.IDataStorage;
import umputun.jutw.twitter.TwitterReadOnly;
import umputun.jutw.utils.common.EasyCipher;
import umputun.jutw.utils.common.UJarInfo;
import umputun.jutw.utils.common.UOpts;
import umputun.jutw.utils.logging.ULogger;

import java.util.LinkedList;
import java.util.List;

/*
 Copyright 2010 Umputun

 This file is part of JUTW.

 JUTW is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 JUTW is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with JUTW.  If not, see http://www.gnu.org/licenses/.
*/


public class Main {

	public static void main(String[] argv) {

		if (argv.length == 0) {
			CheckConfig.findConfig();
		}
		else {
			try {
				ULogger.initLogger("logs/jutw.log");
				logger = ULogger.getLogger();
				new Main(argv);
			}
			catch(Throwable ex) {
				logger.severe("critical error: "+ex.getMessage());
				logger.warning(ULogger.getStackTrace(ex));
				System.exit(1);
			}
		}
	}

	private Main(String[] argv) {
		logger.info("JU-TW Service "+ UJarInfo.getJarInfo("jutw.jar"));
		UOpts params=new UOpts(argv);
		logger.setLevel(ULogger.parseLevel(params.get("dbg", "2")));

		if (params.hasKey("help")) {
			help();
			System.exit(0);
		}
		if (params.hasKey("pgen")) {
			logger.info("password encrypting mode. \nWARNING! this is very, very basic encryption and " +
					"will not provide any real protection");
			String password = params.get("passwd");
			if (password == null) {
				logger.warning("terminated! passwd parameter was not defined");
				System.exit(2);
			}
			System.out.println("encrypted password: [enc]" + ec.encrypt(password)+"[end]");
			System.exit(0);
		}


		TwitterReadOnly twitter = new TwitterReadOnly(
                params.get("tuser").trim(),

                params.get("tckey").trim(),
                params.get("tcsecret").trim(),

                params.get("tkey").trim(),
                params.get("tsecret").trim()
        );

		JabberClient jabber = JabberClient.newBuilder(params.get("jserver").trim())
			.setPassword(decodeIfNeeded(params.get("jpasswd").trim()) )
			.setPort(params.get("jport", 5222))
			.setUser(params.get("jid"))
			.setService(params.get("jservice").trim())
			.build();

		VKActivity vkontakte = null;
		if (params.hasKey("venable")) {
            try {
				if (params.hasKey("vemail") && params.hasKey("vid") && params.hasKey("vpasswd")) {
					vkontakte = new VKActivity(
							params.get("vemail").trim(), params.get("vpasswd").trim());
				}
				else {
					logger.warning("some params missed for vkontakte. disabled");
				}
            }
			catch (Throwable e) {
                logger.warning("vkontakte failed due " + e.getMessage());
            }
        }

		if (params.hasKey("jSelfSignedCertificate"))
			jabber.setSelfSignedCertificateEnabled(params.get("jSelfSignedCertificate", false));

		if (params.hasKey("jNotMatchingDomainCheck"))
			jabber.setNotMatchingDomainCheckEnabled(params.get("jNotMatchingDomainCheck", false));

		if (params.hasKey("jSASLAuthentication"))
			jabber.setSASLAuthenticationEnabled(params.get("jSASLAuthentication", false));

		if (params.hasKey("jSecurityMode"))
			jabber.setSecurityMode(params.get("jSecurityMode", false));

		if (params.hasKey("jReconnection"))
			jabber.setReconnectionAllowed(params.get("jReconnection", false));

		if (params.hasKey("jCompression"))
			jabber.setCompressionEnabled(params.get("jCompression", false));

		if (params.hasKey("jPlain")) {
			jabber.setSASLPlain();
		}

		boolean no_rt = params.hasKey("nort");

		boolean expandLinks = params.hasKey("ExpandLinks");


		List<String> dest_jigs = new LinkedList<String>();
		String[] dest_jids_array = params.get("destjid").split("[\\s;]");
		for(String tmp_jid : dest_jids_array){
			String jid = tmp_jid.trim();
			if(!jid.isEmpty())	{
				dest_jigs.add(jid);
			}
		}

		String jprefix = params.get("jprefix");
		if (jprefix != null)
			logger.info("prefix="+jprefix);

		String jsufix = params.get("jsufix");
		if (jsufix != null)
			logger.info("sufix="+jsufix);

		IDataStorage storage = new FileStorage(params.get("root", ".").trim());
		Processor.Builder bld = Processor.newBuilder(twitter, jabber)
		 .vkontakte(vkontakte)
		 .storage(storage)
		 .to_jids(dest_jigs)
		 .interval(params.get("interval", 300))
		 .jabber_delay(params.get("jdelay", 60))
		 .rt_enable(!no_rt)
		 .expand_links(expandLinks)
		 .jprefix(jprefix)
		 .jsufix(jsufix);

		Processor proc = bld.build();
		proc.activate();
	}

	private String decodeIfNeeded(String input) {
		if (input.startsWith("[enc]") && input.length()>5)
			return ec.decrypt(input.substring(5, input.length()-5));
		return input;
	}

	private void help() {
		System.out.println("java -jar jutw.jar --opts=<options file> --dbg=<0..3>");
		System.out.println("for options file details see http://code.google.com/p/jutw/wiki/InstallJutw");
	}

	private final EasyCipher ec = new EasyCipher("JU-TW Service vErY Secure Key#1. Heh :) ");
	private static ULogger logger;
}
